/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.dao.jpa;

import com.jmooc.dao.AnswerDao;
import com.jmooc.entity.Answer;
import com.jmooc.entity.Answer_;
import com.jmooc.entity.Question;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Group
 */
@Stateless
public class JpaAnswerDao implements AnswerDao {
    
    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Answer> getAllByQuestion(Question question) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Answer> query = cb.createQuery(Answer.class);
        Root<Answer> answer = query.from(Answer.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(answer.get(Answer_.question), question)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();
        //return em.createQuery("SELECT a from Answer a WHERE a.question = :q").setParameter("q", question).getResultList();
    }

    @Override
    public void create(Answer answer) {
        em.persist(answer);
    }

}
